package com.xuzhiguang.lightnat.client.transfer.processor;

import com.xuzhiguang.lightnat.common.manager.TransferChannelManager;
import com.xuzhiguang.lightnat.common.message.MessageProcessor;
import com.xuzhiguang.lightnat.common.message.NatMessage;
import com.xuzhiguang.lightnat.common.message.transfer.TransferAuthenticationResponse;
import io.netty.channel.ChannelHandlerContext;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Data
public class TransferAuthenticationResponseProcessor implements MessageProcessor {

    private TransferAuthenticationListener transferAuthenticationListener;

    @Override
    public void process(ChannelHandlerContext ctx, NatMessage natMessage) {

        log.debug("transfer TransferAuthenticationResponseProcessor. channel:{}", ctx.channel());

        if (natMessage.getBody() instanceof TransferAuthenticationResponse) {
            TransferAuthenticationResponse response = (TransferAuthenticationResponse) natMessage.getBody();

            if (response.getSuccess()) {
                TransferChannelManager.add(response.getTransferId(), ctx.channel());
                log.info("transfer client auth success. transferId:{}", response.getTransferId());
            } else {
                log.warn("transfer client auth fail. error msg:{}", response.getErrMsg());
            }

            if (transferAuthenticationListener != null) {
                transferAuthenticationListener.complete(ctx.channel(), response.getSuccess(), response.getErrMsg());
            }

        }
    }
}
